<template>
  <div id="app">
    <XWebSocket ref="XWebSocket"></XWebSocket>
    <router-view></router-view>
  </div>
</template>

<script>
import { mapActions } from "vuex";
export default {
  name: "App",
  data() {
    return {
      onLine: navigator.onLine,
    };
  },
  components: {
    XWebSocket: () =>
      import(
        /* webpackChunkName:'xwebSocket' */ "@/components/baseComponents/webSocket/index.vue"
      ),
  },
  created() {
    // 监听网络
    // 网络由异常到正常时触发
    window.addEventListener("online", this.updateOnlineStatus, false);
    // 网络由正常到异常触发
    window.addEventListener("offline", this.updateOfflineStatus, false);
  },
  mounted() {
    this.setNetStatus({ onLine: this.onLine });
  },
  destroyed() {
    // 监听网络
    // 网络由异常到正常时触发
    window.removeEventListener("online", this.updateOnlineStatus, false);
    // 网络由正常到异常触发
    window.removeEventListener("offline", this.updateOfflineStatus, false);
  },
  methods: {
    ...mapActions(["setNetStatus"]),
    updateOnlineStatus() {
      console.warn("网络连接成功");
      this.onLine = true;
      this.$refs["XWebSocket"].createSocket();
      this.setNetStatus({ onLine: this.onLine });
    },
    updateOfflineStatus() {
      console.warn("网络断开连接");
      this.onLine = false;
      this.setNetStatus({ onLine: this.onLine });
    },
  },
};
</script>

<style lang="scss" scoped>
html {
  body {
    padding: 0;
    margin: 0;
    #app {
      font-family: Avenir, Helvetica, Arial, sans-serif;
    }
  }
}
</style>
